<script setup>
import {onMounted, ref} from 'vue'
import {formatConfig, getGameConfig, saveGameConfig} from "src/utils/config";
import {Dialog, Notify, Loading} from "quasar";
import {cloud} from 'boot/weixin'
import moment from 'moment'

let config_id = ''
const game_config = ref({})
const config_json = ref('')
const loading = ref([
  false,
  false,
  false,
  false,
  false,
  false
])
const engine_name = [
  {label: '建字库', value: 'wxa197cb55955c4f3f'},
  {label: '博物馆', value: 'wx7f4640fff2b3f7fa'},
  {label: '暗战', value: 'wx669785dcf46b4df6'},
]

onMounted(() => {
  // 从本地缓存读取游戏配置
  loadConfigFromLocal()
})

function loadConfigFromLocal() {
  const config = getGameConfig()
  // console.log('config id', config._id)
  if (config === null) {
    return
  }

  config_id = config._id

  // UI显示
  game_config.value = config
  config_json.value = JSON.stringify(config, null, '\t')
}

async function onChangeInfo() {
  console.log('change info')
  const temp_config = JSON.parse(JSON.stringify(game_config.value))
  config_json.value = JSON.stringify(temp_config, null, '\t')
}

async function saveToRemote() {
  const temp_config = JSON.parse(config_json.value)
  console.log('config id', config_id)
  console.log('save to remote', temp_config)

  // 检查code是否重复
  const db = cloud.database()
  const res = await db.collection('project').where({
    code: game_config.value.code
  }).field({code: true,}).get()
  console.log('config db', res.data)

  if (res.data.length === 1) {
    if (res.data[0]._id !== config_id) {
      return Dialog.create({
        title: '提示',
        message: '邀请码重复',
      })
    }
  }

  // 替换基础数据
  temp_config._id = game_config.value._id
  temp_config.code = game_config.value.code
  temp_config.title = game_config.value.title
  temp_config.memo = game_config.value.memo
  temp_config.appid = game_config.value.appid

  // 格式化数据
  const config = formatConfig(temp_config)
  console.log('formated config', config)

  Dialog.create({
    title: '提示',
    message: '远程数据将被覆盖，请再次输入邀请码：',
    prompt: {
      model: '',
      type: 'text' // optional
    }, cancel: true,
    persistent: true
  }).onOk((data) => {
    if (data !== config.code) {
      return Dialog.create({
        title: '提示',
        message: '邀请码不一致，请再次确认'
      })
    }

    Loading.show({
      message: 'waiting...'
    })
    loading.value[2] = true

    console.log('save config2db', config)
    db.collection('project').doc(config._id).update({
      code: config.code,
      version: config.version,
      title: config.title,
      memo: config.memo,
      appid: config.appid,
      page: JSON.stringify(config.page),
      checkpoint_list: JSON.stringify(config.checkpoint_list),
      flow_list: config.flow_list,
    }).then(() => {
      Loading.hide()
      Notify.create({
        message: '保存成功'
      })

      // 保存到本地
      saveGameConfig(config)

      // 重新加载本地数据
      loadConfigFromLocal()

      loading.value[2] = false
    }).catch((e) => {
      Loading.hide()
      Notify.create({
        message: '保存服务器数据失败：' + e
      })
      loading.value[2] = false
    })
  })
}

function exportData() {
  const temp_filename = game_config.value.code + '(' + new Date().toISOString().slice(0, 10) + ')'
  Dialog.create({
    title: '提示',
    message: '输入文件名：',
    prompt: {
      model: temp_filename,
      type: 'text' // optional
    },
    cancel: true,
    persistent: true
  }).onOk((json_filename) => {
    // const list = getCheckpointList();
    const config = getGameConfig()
    const dataStr = "data:text/json;charset=utf-8," + encodeURIComponent(JSON.stringify(config, null, '\t'));
    const downloadAnchorTag = document.createElement('a');
    downloadAnchorTag.setAttribute('href', dataStr);
    downloadAnchorTag.setAttribute('download', json_filename + '.json');
    document.body.appendChild(downloadAnchorTag);
    downloadAnchorTag.click();
    document.body.removeChild(downloadAnchorTag);
    Dialog.create({
      title: '提示',
      message: '保存完毕，请妥善保存该文件'
    })
  })
}

function importData() {
  const config = getGameConfig()

  Dialog.create({
    title: '提示',
    message: '本地数据将被覆盖，请再次输入邀请码：',
    prompt: {
      model: '',
      type: 'text' // optional
    },
    cancel: true,
    persistent: true
  }).onOk((data) => {
    if (data !== config.code) {
      return Dialog.create({
        title: '提示',
        message: '邀请码不一致，请再次确认'
      })
    }

    try {
      const import_config = JSON.parse(config_json.value)

      // 确保游戏基本信息不改变
      import_config._id = config._id
      import_config.code = data

      // 标记是导入数据
      import_config.memo += "\nimport-" + moment(new Date()).format('YYYY年MM月DD日')

      // 保存到本地
      saveGameConfig(import_config)
      loadConfigFromLocal()

      Notify.create({
        message: '成功导入数据'
      })
    } catch (e) {
      Notify.create({
        message: '转化数据失败:' + e
      })
    }
  })

}

function updateData() {
  loading.value[3] = true

  // 更新
  const config = formatConfig(getGameConfig())
  saveGameConfig(config)
  loadConfigFromLocal()
  // const config = getGameConfig()
  //
  // config.flow_list.forEach(function (checkpoint) {
  //   console.log(checkpoint.name)
  //   checkpoint.flow.nodes.forEach(function (node) {
  //     if (node.data.type !== 101) return
  //     console.log(checkpoint.gps, node.data.gps, node.data.range)
  //     node.data.gps = checkpoint.gps
  //     node.data.range = 35
  //   })
  // })
  //
  // saveGameConfig(config)

  loading.value[3] = false
}

</script>

<template>
  <q-page class="q-pa-md">
    <q-list bordered separator>
      <q-item>
        <q-card class="my-card">
          <!--          <q-card-section class="bg-primary text-white">-->
          <!--            <div class="text-h6">基础信息</div>-->
          <!--          </q-card-section>-->

          <!--          <q-separator/>-->

          <q-card-section>
            <q-input
              v-model="game_config.code"
              label="游戏邀请码"
              debounce="1000"
              @update:model-value="onChangeInfo"
            ></q-input>
          </q-card-section>

          <q-card-section>
            <q-input
              v-model="game_config.title"
              label="游戏名"
              debounce="1000"
              @update:model-value="onChangeInfo"
            ></q-input>
          </q-card-section>

          <q-card-section>
            <q-select
              v-model="game_config.appid"
              :options="engine_name"
              emit-value
              map-options
              @update:model-value="onChangeInfo"
              label="游戏引擎"/>
          </q-card-section>

          <q-card-section>
            数据版本：{{ game_config.version }}
          </q-card-section>

        </q-card>

        <q-card class="my-card ">
          <q-card-section>
            <q-input
              type="textarea"
              rows="8"
              v-model="game_config.memo"
              label="备注"
              debounce="1000"
              @update:model-value="onChangeInfo"
            ></q-input>
          </q-card-section>

          <q-card-section>
            开始时间：{{ $moment(game_config.beginDate).format('YYYY年MM月DD日') }}
          </q-card-section>

          <q-card-section>
            结束时间：{{ $moment(game_config.endDate).format('YYYY年MM月DD日') }}
          </q-card-section>

        </q-card>
      </q-item>

      <q-item>
        <q-card class="config-json">
          <q-card-section class="bg-primary text-white">
            <div class="text-h6">原始数据</div>
          </q-card-section>

          <q-separator/>

          <q-card-section>
            <q-input type="textarea" rows="20" v-model="config_json"></q-input>
          </q-card-section>

          <q-card-actions align="right">
            <q-btn color="purple" :loading="loading[2]" @click="saveToRemote" label="保存到服务器">
              <template v-slot:loading>
                <q-spinner-hourglass class="on-left"/>
                Loading...
              </template>
            </q-btn>
            <!--            <q-btn :loading="loading[3]" color="purple" @click="updateData" label="格式化数据" style="width: 150px">-->
            <!--              <template v-slot:loading>-->
            <!--                <q-spinner-hourglass class="on-left"/>-->
            <!--                Loading...-->
            <!--              </template>-->
            <!--            </q-btn>-->
<!--            <q-btn color="purple" @click="importData" label="导入数据"/>-->
            <q-btn color="purple" @click="exportData" label="导出数据"/>
          </q-card-actions>
        </q-card>
      </q-item>

    </q-list>

  </q-page>

</template>

<style scoped>
.my-card {
  width: 50vw;
  margin: 20px
}

.config-json {
  width: 100vw;
  margin: 20px
}
</style>
